package org.tnc.budget.webapp.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.tnc.budget.model.BudgetCenter;
import org.tnc.budget.service.BudgetManager;
import org.tnc.model.User;
import org.tnc.service.UserManager;
import org.tnc.webapp.controller.MessageBaseController;

/**
 * 预算中心后台管理程序WEB接口 <br />
 * 
 * 1. 查询所有的预算中心 <br />
 * 
 * @author houjj | 2011-4-5 上午09:44:38
 */
@Controller
public class BudgetManagerController extends MessageBaseController {

	private Logger log = Logger.getLogger(BudgetManagerController.class);

	private BudgetManager budgetManager;
	private UserManager userManager;
	
	/**
	 * 查询预算中心列表
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/budget/budlist")
	public String getBudgetList(HttpServletRequest request,
			HttpServletResponse response, Map model) {
		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		getBudgetList(request, user);
		return "/budget/budlist";
	}

	/**
	 * 删除预算中心
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/budget/delBudgetInfo")
	public String delBudgetInfo(HttpServletRequest request,
			HttpServletResponse response, @RequestParam Integer id, Map model) {
		if (log.isDebugEnabled())
			log.debug("Delete budget info start ...");

		boolean result = false;
		try {
			if (id > 0)
				result = this.budgetManager.delete(id);
		} catch (Exception e) {
			log.error("Delete budget info failed, id:" + id);
			result = false;
		}
		// 操作消息提示
		if (result) {
			this.saveMessage(request,
					getText("budget.info.delete.success", request.getLocale()));
		} else {
			this.saveError(request,
					getText("budget.info.delete.failed", request.getLocale()));
		}
		// 重新检索有效的列表
		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		getBudgetList(request, user);

		return "/budget/budlist";
	}

	/**
	 * 创建新预算中心的页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/budget/newBudget")
	public String addBudgetInfo(HttpServletRequest request,
			HttpServletResponse response) {

		List<User> users = this.userManager.getUsers();
		request.setAttribute("users", users);

		return "/budget/newBudget";
	}

	/**
	 * 创建新的预算中心
	 * 
	 * @param request
	 * @param response
	 * @param budgetInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/budget/addBudgetInfo", method = {RequestMethod.POST, RequestMethod.GET})
	public String addBudgetInfo(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		BudgetCenter budgetInfo = wrapBudgetCenter(request);
		if (budgetInfo == null || budgetInfo.getBcName() == null
				|| budgetInfo.getBcId() == null) {
			return "redirect:/budget/newBudget.html";
		}

		// 检查预算中心的名称是否已经存在
		String bcName = budgetInfo.getBcName();
		BudgetCenter bc = this.budgetManager.getBudgetByName(bcName);
		if (bc != null) {
			request.setAttribute("budgetInfo", budgetInfo);
			this.saveError(
					request,
					getText("budget.info.name.already.exist", bcName,
							request.getLocale()));

			List<User> users = this.userManager.getUsers();
			request.setAttribute("users", users);

			return "/budget/newBudget";
		}

		// 检查预算中心编号重复问题
		String bcId = budgetInfo.getBcId();
		BudgetCenter bcIds = this.budgetManager.getBudgetByBcId(bcId);
		if (bcIds != null) {
			request.setAttribute("budgetInfo", budgetInfo);
			this.saveError(
					request,
					getText("budget.info.bcid.already.exist", bcId,
							request.getLocale()));

			List<User> users = this.userManager.getUsers();
			request.setAttribute("users", users);

			return "/budget/newBudget";
		}
		
		// 判断责任人是否存在
		User bcDuty = budgetInfo.getUser();
		if(bcDuty == null)
		{
			this.saveError(
					request,
					getText("login.signup", bcId,
							request.getLocale()));
			
			List<User> users = this.userManager.getUsers();
			request.setAttribute("users", users);
			
			return "/budget/newBudget";
		}

		// 创建新的预算中心
		User u = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		budgetInfo.setBcPeople(u.getEmail());
		budgetInfo.setBcDate(new Date());
		budgetInfo.setBcValid(true);
		try {
			this.budgetManager.save(budgetInfo);
			this.saveMessage(request,
					getText("budget.info.new.success", request.getLocale()));

		} catch (Exception e) {
			log.error("Update budget info failed , user:" + u.getEmail()
					+ ", budget name:" + budgetInfo.getBcName());
			this.saveError(
					request,
					getText("budget.info.new.failed", budgetInfo.getBcName(),
							request.getLocale()));
		
		}
		
		
		
		getBudgetList(request, u);
		return "/budget/budlist";
	}
	


	private BudgetCenter wrapBudgetCenter(HttpServletRequest request) {
		String bcId = request.getParameter("bcId");
		String bcName = request.getParameter("bcName");
		String userId = request.getParameter("user.id");
		String bcDec = request.getParameter("bcDec");
		String vacation = request.getParameter("vacation");
		
		BudgetCenter bc = new BudgetCenter();
		bc.setBcId(bcId);
		bc.setBcName(bcName);
		bc.setUser(this.userManager.getUser(userId));
		bc.setBcDec(bcDec);
		bc.setVacation(Boolean.valueOf(vacation));
		return bc;
	}

	@RequestMapping(value = "/budget/getBudgetInfo")
	public String getBudgetInfo(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("id") Integer id, Map model) {
		BudgetCenter bc = this.budgetManager.getBudgetById(id);
		if (bc == null) {
			this.saveError(request,
					getText("budget.info.error.not.exist", request.getLocale()));
		} else {
			List<User> users = this.userManager.getUsers();
			request.setAttribute("users", users);

			request.setAttribute("budgetInfo", bc);

		}
		return "/budget/budgetInfo";
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @param budgetInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/budget/updateBudgetInfo")
	public String updateBudgetInfo(HttpServletRequest request,
			HttpServletResponse response, BudgetCenter budgetInfo, Map model) {

		if (budgetInfo == null || budgetInfo.getBcId() == null
				|| budgetInfo.getBcName() == null) {
			return "redirect:/budget/budlist.html";
		}

		int id = budgetInfo.getId();
		BudgetCenter bc = null;
		if(id > 0)
		{
			bc = this.budgetManager.getBudgetById(id);
			
			if(bc == null)
			{
				request.setAttribute("budgetInfo", budgetInfo);
				this.saveError(
						request,
						getText("budget.info.error.not.exist", request.getLocale()));
				return "/budget/budgetInfo";
			}
		}

		// 判断责任人是否存在
		String userId = request.getParameter("bcDuty");
		User u = this.userManager.getUser(userId);
		if(u == null)
		{
			this.saveError(
					request,
					getText("login.signup", userId,
							request.getLocale()));
			
			List<User> users = this.userManager.getUsers();
			request.setAttribute("users", users);
			
			return "/budget/budgetInfo";
		} else {
			budgetInfo.setUser(u);
		}
		
		bc.setBcId(budgetInfo.getBcId());
		bc.setBcDec(budgetInfo.getBcDec());
		bc.setBcName(budgetInfo.getBcName());
		bc.setUser(u);
		bc.setVacation(budgetInfo.getVacation());

		
		try {	
			this.budgetManager.update(bc);
			this.saveMessage(request,
					getText("budget.info.update.success", request.getLocale()));

		} catch (Exception e) {
			log.error("Update budget info failed , user:" + u.getEmail()
					+ ", budget name:" + budgetInfo.getBcName(), e);
			this.saveMessage(
					request,
					getText("budget.info.update.failed",
							budgetInfo.getBcName(), request.getLocale()));
		}

		User user = (User) SecurityContextHolder.getContext()
		.getAuthentication().getPrincipal();
		getBudgetList(request, user);
		return "/budget/budlist";
	}

	private void getBudgetList(HttpServletRequest request, User user) {
		
		boolean isAdmin = isRoleAdmin(user);
		List<BudgetCenter> budgetList = budgetManager.getAll(!isAdmin, null);
		if (budgetList == null)
			budgetList = new ArrayList<BudgetCenter>();

		request.setAttribute("budgetList", budgetList);
	}

	private boolean isRoleAdmin(User user) {
		boolean result = false;
		GrantedAuthority[] ga = user.getAuthorities();
		for (GrantedAuthority grantedAuthority : ga) {
			String authority = grantedAuthority.getAuthority();
			if ("ROLE_ADMIN".equals(authority)) {
				result = true;
				break;
			}
		}
		return result;
	}

	public void setBudgetManager(BudgetManager budgetManager) {
		this.budgetManager = budgetManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

}
